<template>
  <div class="loginBox">
    <teleport to=".header">
      <shopHeader title="登录" />
    </teleport>

    <van-form @submit="loginHandler" class="login">
      <van-cell-group inset>
        <van-field
          v-model="userinfo.loginname"
          name="loginname"
          label="用户名"
          aautocomplete="off"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <div class="pwd">
          <van-field
            autocomplete="off"
            v-model="userinfo.password"
            :type="is_eyes ? 'text' : 'password'"
            name="password"
            label="密码"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <van-icon v-if="is_eyes" @click="is_eyes = false" name="browsing-history-o" class="eye"/>
          <van-icon v-else @click="is_eyes = true" name="closed-eye" class="eye"/>
        </div>
     
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>

    <van-divider :style="{ borderColor: '#1989fa', width: '100%' }">其他</van-divider>

    <p>还没有账号，<router-link to="/register">去注册</router-link></p>
  </div>
</template>
<script setup lang="ts">
import { showSuccessToast, showFailToast } from 'vant'
import { login } from "../../request/user"
import shopHeader from "../../components/header.vue"
import { ref } from "vue"
import { useRouter } from 'vue-router'
const $myRouter = useRouter()

const is_eyes = ref<boolean>(true)

interface User{
  loginname?: string,
  password?: string
}
interface Reponse{
  code: string,
  message: string
  data?: {
    token: string,
    userid: string
  }
}

const userinfo = ref<User>({loginname: '', password: ''})
const loginHandler = async (info: User) => {
  const res = await login(info)
  if((res as unknown as Reponse).code === '10010'){
     showFailToast((res as unknown as Reponse).message)
     return
  }
  if((res as unknown as Reponse).code === '10011'){
     showFailToast('用户名或密码错误')
     return
  }
  if((res as unknown as Reponse).code !== '200')showFailToast('登录失败')

  window.localStorage.setItem('token', res.data.token)
  window.localStorage.setItem('user_id', res.data.userid)

  showSuccessToast('登录成功')
  $myRouter.push('/home')
}
</script>


<style scoped lang="scss">
.pwd{
  position: relative;
  .eye{
    position: absolute;
    top: 13px;
    right: 0;
  }
}

.loginBox{
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  .login{
    width: 85%;
    border: 1px solid #666;
    border-radius: 5px;
  }
}
</style>
